package handle

import (
	"duanju-mq/db"
	"duanju-mq/pkg/log"
	"duanju-mq/pkg/redis"
	"duanju-mq/pkg/util/convert"
	"encoding/json"
	"fmt"
)

const (
	userUnlockHistoryCacheDataPrefix = "userUnlockHistoryData_"
)

type unlockHistory struct {
	DeviceId       string  `json:"device_id"`
	CreateAt       int64   `json:"create_at"`
	MatutiryTime   int64   `json:"matutiry_time"`
	FilmEpisodesId int64   `json:"film_episodes_id"`
	Status         int64   `json:"status"`
	Reason         string  `json:"reason"`
	Url            string  `json:"url"`
	Size           int     `json:"size"`
	Duration       int     `json:"duration"`
	FilmId         int64   `json:"film_id"`
	FilmName       string  `json:"film_name"`
	EpisodeNo      int     `json:"episode_no"`
	Coins          int64   `json:"coins"`
	Bonus          int64   `json:"bonus"`
	Price          float64 `json:"price"`
}

type filmEpisodesRsp struct {
	DeviceId  string `json:"device_id"`
	FilmId    int64  `json:"film_id"`
	Id        int64  `json:"id" field:"film_episodes.id"`
	EpisodeNo int    `json:"episode_no" field:"film_episodes.episode_no"`
	Expired   int64  `json:"expired" field:"unlock_order.expired"` //购买影片后的有效观看期限
}

func HandleUnlockHistory(rawData string) {

	info := unlockHistory{}
	if err := json.Unmarshal([]byte(rawData), &info); err != nil {
		log.Err(fmt.Sprintf("HandleUnlockHistory json.Unmarshal value:%v err:%+v", rawData, err))
		return
	}

	d := &redis.ZData{
		Score:  info.CreateAt,
		Member: rawData,
	}
	rows := []*redis.ZData{d}

	sysRedis := db.SysRedis()
	key := fmt.Sprintf("%v%v", userUnlockHistoryCacheDataPrefix, info.DeviceId)
	if err := sysRedis.Zset(key).ZAdd(rows...).Error(); err != nil {
		log.Err(fmt.Sprintf("设置用户 %+v 影片章节解锁历史失败:values:%v err:%+v", info.DeviceId, rawData, err))
		return
	}
}

func HandleUnlockFilmEpisodes(rawData string) {

	info := filmEpisodesRsp{}

	if err := json.Unmarshal([]byte(rawData), &info); err != nil {
		log.Err(fmt.Sprintf("HandleUnlockFilmEpisodes json.Unmarshal value:%v err:%+v", rawData, err))
		return
	}

	//用户的影片章节解锁情况，以影片为单位
	zsetKey := fmt.Sprintf("unlocked_film_episodes_%v_%v", info.DeviceId, info.FilmId)
	data := &redis.ZData{Score: int64(convert.Atoi(fmt.Sprintf("%v", info.EpisodeNo))), Member: rawData}
	if err := db.SysRedis().Zset(zsetKey).ZAdd(data).Error(); err != nil {
		log.Err(fmt.Sprintf("更新用户%v的解锁影片数据失败", info.DeviceId))
	}

}
